<template>
  <div class="order-taking">
    <div class="game-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
      <div class="game-title">
        <h1>🍽️ 点餐服务游戏</h1>
        <p>快速准确地处理客人点餐，提升服务效率和准确率</p>
      </div>
      <div class="game-stats">
        <el-statistic title="正确率" :value="gameStats.accuracy" suffix="%" />
        <el-statistic title="服务客人" :value="gameStats.servedCustomers" />
        <el-statistic title="获得积分" :value="gameStats.points" />
      </div>
    </div>

    <!-- 游戏开始界面 -->
    <div v-if="!gameStarted" class="start-screen">
      <div class="game-intro">
        <h2>游戏说明</h2>
        <div class="rules">
          <div class="rule-item">
            <el-icon><Clock /></el-icon>
            <p>根据客人的口述，快速选择正确的菜品</p>
          </div>
          <div class="rule-item">
            <el-icon><Select /></el-icon>
            <p>注意菜品的特殊要求（辣度、温度等）</p>
          </div>
          <div class="rule-item">
            <el-icon><TrendCharts /></el-icon>
            <p>准确率越高，获得的积分越多</p>
          </div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon>
            <p>错误三次游戏结束</p>
          </div>
        </div>
        <el-button type="primary" size="large" @click="startGame">
          开始游戏
        </el-button>
      </div>
    </div>

    <!-- 游戏进行界面 -->
    <div v-else class="game-screen">
      <div class="game-info-bar">
        <div class="timer">
          <el-icon><Timer /></el-icon>
          剩余时间: {{ remainingTime }}s
        </div>
        <div class="score">
          <el-icon><Trophy /></el-icon>
          得分: {{ currentScore }}
        </div>
        <div class="combo">
          <el-icon><Lightning /></el-icon>
          连击: {{ combo }}
        </div>
        <div class="mistakes">
          <el-icon><CircleClose /></el-icon>
          错误: {{ mistakes }}/3
        </div>
      </div>

      <!-- 餐厅场景 -->
      <div class="restaurant-scene">
        <!-- 当前客人 -->
        <div class="current-customer">
          <el-avatar :src="currentCustomer.avatar" :size="100" />
          <div class="speech-bubble">
            <p class="customer-speech">{{ currentOrder.speech }}</p>
            <div class="special-requirements" v-if="currentOrder.requirements.length > 0">
              <el-tag 
                v-for="req in currentOrder.requirements" 
                :key="req"
                type="warning"
                size="small"
              >
                {{ req }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 菜单选择区 -->
        <div class="menu-grid">
          <div 
            v-for="dish in menuOptions" 
            :key="dish.id"
            class="dish-card"
            :class="{ 
              selected: selectedDishes.includes(dish.id),
              correct: showResult && isCorrectDish(dish.id),
              wrong: showResult && selectedDishes.includes(dish.id) && !isCorrectDish(dish.id)
            }"
            @click="!showResult && selectDish(dish)"
          >
            <div class="dish-image">{{ dish.emoji }}</div>
            <h4>{{ dish.name }}</h4>
            <p class="dish-price">¥{{ dish.price }}</p>
            <div class="dish-tags">
              <el-tag 
                v-for="tag in dish.tags" 
                :key="tag"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            <el-icon v-if="showResult && isCorrectDish(dish.id)" class="result-icon correct">
              <CircleCheck />
            </el-icon>
            <el-icon v-if="showResult && selectedDishes.includes(dish.id) && !isCorrectDish(dish.id)" class="result-icon wrong">
              <CircleClose />
            </el-icon>
          </div>
        </div>

        <!-- 确认按钮 -->
        <div class="actions" v-if="!showResult">
          <el-button 
            type="primary" 
            size="large"
            :disabled="selectedDishes.length === 0"
            @click="confirmOrder"
          >
            确认点餐
          </el-button>
          <el-button size="large" @click="clearSelection">
            清空选择
          </el-button>
        </div>

        <!-- 结果显示 -->
        <div class="result-panel" v-if="showResult">
          <el-alert
            :title="resultMessage"
            :type="resultType"
            :closable="false"
            show-icon
            :description="`${resultDetail}`"
          />
          <el-button 
            type="primary" 
            size="large"
            @click="nextRound"
            class="next-btn"
          >
            下一位客人 ({{ nextRoundCountdown }}s)
          </el-button>
        </div>
      </div>
    </div>

    <!-- 游戏结束对话框 -->
    <el-dialog
      v-model="showGameOverDialog"
      title="游戏结束"
      width="600px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="game-over">
        <div class="final-score">
          <h2>最终得分</h2>
          <div class="score-display">{{ finalScore }}</div>
        </div>
        <div class="game-stats-summary">
          <div class="stat-item">
            <span>服务客人:</span>
            <strong>{{ servedCount }}</strong>
          </div>
          <div class="stat-item">
            <span>正确订单:</span>
            <strong>{{ correctCount }}</strong>
          </div>
          <div class="stat-item">
            <span>准确率:</span>
            <strong>{{ Math.round((correctCount / servedCount) * 100) }}%</strong>
          </div>
          <div class="stat-item">
            <span>最高连击:</span>
            <strong>{{ maxCombo }}</strong>
          </div>
        </div>
        <el-alert
          :title="`获得 ${finalScore} 积分！`"
          type="success"
          :closable="false"
          show-icon
        />
      </div>
      <template #footer>
        <el-button @click="restartGame">再玩一次</el-button>
        <el-button type="primary" @click="goBack">返回游戏中心</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, Clock, Select, TrendCharts, Warning,
  Timer, Trophy, Lightning, CircleClose, CircleCheck
} from '@element-plus/icons-vue'

const router = useRouter()

// 游戏统计
const gameStats = ref({
  accuracy: 95,
  servedCustomers: 126,
  points: 2580
})

// 游戏状态
const gameStarted = ref(false)
const remainingTime = ref(60)
const currentScore = ref(0)
const combo = ref(0)
const maxCombo = ref(0)
const mistakes = ref(0)
const servedCount = ref(0)
const correctCount = ref(0)
const showResult = ref(false)
const showGameOverDialog = ref(false)
const selectedDishes = ref([])
const nextRoundCountdown = ref(3)
const finalScore = ref(0)

// 当前客人
const currentCustomer = ref({
  avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
  name: '张先生'
})

// 菜品库
const allDishes = [
  { id: 1, name: '宫保鸡丁', emoji: '🍗', price: 38, tags: ['川菜', '辣', '鸡肉'], category: '热菜' },
  { id: 2, name: '麻婆豆腐', emoji: '🍲', price: 28, tags: ['川菜', '辣', '豆腐'], category: '热菜' },
  { id: 3, name: '糖醋排骨', emoji: '🍖', price: 48, tags: ['酸甜', '猪肉'], category: '热菜' },
  { id: 4, name: '番茄炒蛋', emoji: '🍅', price: 22, tags: ['家常菜', '蛋'], category: '热菜' },
  { id: 5, name: '清蒸鲈鱼', emoji: '🐟', price: 58, tags: ['清淡', '鱼'], category: '海鲜' },
  { id: 6, name: '水煮鱼', emoji: '🐠', price: 68, tags: ['川菜', '特辣', '鱼'], category: '海鲜' },
  { id: 7, name: '凉拌黄瓜', emoji: '🥒', price: 12, tags: ['凉菜', '清淡'], category: '凉菜' },
  { id: 8, name: '皮蛋豆腐', emoji: '🥚', price: 18, tags: ['凉菜', '豆腐'], category: '凉菜' },
  { id: 9, name: '蛋炒饭', emoji: '🍚', price: 20, tags: ['主食', '蛋'], category: '主食' },
  { id: 10, name: '牛肉面', emoji: '🍜', price: 25, tags: ['主食', '牛肉', '面'], category: '主食' },
  { id: 11, name: '小笼包', emoji: '🥟', price: 18, tags: ['点心', '猪肉'], category: '点心' },
  { id: 12, name: '珍珠奶茶', emoji: '🧋', price: 15, tags: ['饮品', '甜'], category: '饮品' },
  { id: 13, name: '鲜榨西瓜汁', emoji: '🍉', price: 12, tags: ['饮品', '果汁'], category: '饮品' },
  { id: 14, name: '可乐', emoji: '🥤', price: 8, tags: ['饮品', '碳酸'], category: '饮品' },
  { id: 15, name: '红烧牛肉', emoji: '🥩', price: 52, tags: ['热菜', '牛肉'], category: '热菜' },
  { id: 16, name: '青椒肉丝', emoji: '🫑', price: 32, tags: ['家常菜', '猪肉'], category: '热菜' }
]

// 订单库
const orderTemplates = [
  {
    speech: '我要一份辣的，里面有鸡肉的菜，再来一杯可乐',
    correctDishes: [1, 14],
    requirements: ['辣', '有鸡肉']
  },
  {
    speech: '来一份不辣的鱼，要清淡的那种，再来一份炒饭',
    correctDishes: [5, 9],
    requirements: ['不辣', '清淡']
  },
  {
    speech: '我想吃川菜，要两个辣的，一个豆腐一个鱼',
    correctDishes: [2, 6],
    requirements: ['川菜', '辣']
  },
  {
    speech: '点一份面，要牛肉的，再来两个凉菜',
    correctDishes: [10, 7, 8],
    requirements: ['牛肉', '凉菜']
  },
  {
    speech: '来一个酸甜口味的肉，再来一份主食和一杯奶茶',
    correctDishes: [3, 9, 12],
    requirements: ['酸甜', '主食']
  },
  {
    speech: '我要吃辣的豆腐，再来一个清淡的黄瓜',
    correctDishes: [2, 7],
    requirements: ['辣', '清淡']
  },
  {
    speech: '给我来一份红烧的牛肉，再来一个点心',
    correctDishes: [15, 11],
    requirements: ['牛肉', '点心']
  },
  {
    speech: '我想喝果汁，再来一份不辣的家常菜',
    correctDishes: [13, 4],
    requirements: ['果汁', '不辣']
  }
]

// 当前订单
const currentOrder = ref(generateNewOrder())

// 菜单选项（从所有菜品中随机选择）
const menuOptions = ref(getRandomDishes())

// 结果信息
const resultMessage = ref('')
const resultType = ref('success')
const resultDetail = ref('')

// 生成新订单
function generateNewOrder() {
  const template = orderTemplates[Math.floor(Math.random() * orderTemplates.length)]
  return {
    ...template
  }
}

// 获取随机菜品（包含正确答案和干扰项）
function getRandomDishes() {
  const correctDishes = currentOrder.value.correctDishes.map(id => 
    allDishes.find(d => d.id === id)
  )
  
  // 添加干扰项
  const otherDishes = allDishes
    .filter(d => !currentOrder.value.correctDishes.includes(d.id))
    .sort(() => Math.random() - 0.5)
    .slice(0, 9 - correctDishes.length)
  
  return [...correctDishes, ...otherDishes].sort(() => Math.random() - 0.5)
}

// 是否是正确的菜品
function isCorrectDish(dishId) {
  return currentOrder.value.correctDishes.includes(dishId)
}

// 开始游戏
function startGame() {
  gameStarted.value = true
  remainingTime.value = 60
  currentScore.value = 0
  combo.value = 0
  maxCombo.value = 0
  mistakes.value = 0
  servedCount.value = 0
  correctCount.value = 0
  
  // 开始计时
  const timer = setInterval(() => {
    if (remainingTime.value > 0 && gameStarted.value && !showGameOverDialog.value) {
      remainingTime.value--
    } else {
      clearInterval(timer)
      if (gameStarted.value) {
        endGame()
      }
    }
  }, 1000)
}

// 选择菜品
function selectDish(dish) {
  const index = selectedDishes.value.indexOf(dish.id)
  if (index > -1) {
    selectedDishes.value.splice(index, 1)
  } else {
    selectedDishes.value.push(dish.id)
  }
}

// 清空选择
function clearSelection() {
  selectedDishes.value = []
}

// 确认订单
function confirmOrder() {
  showResult.value = true
  servedCount.value++
  
  // 检查答案
  const correct = currentOrder.value.correctDishes.length
  const selected = selectedDishes.value.length
  const correctSelected = selectedDishes.value.filter(id => 
    currentOrder.value.correctDishes.includes(id)
  ).length
  
  if (correctSelected === correct && selected === correct) {
    // 完全正确
    correctCount.value++
    combo.value++
    maxCombo.value = Math.max(maxCombo.value, combo.value)
    
    const points = 100 + combo.value * 10
    currentScore.value += points
    
    resultType.value = 'success'
    resultMessage.value = '✨ 完美！订单完全正确！'
    resultDetail.value = `获得 ${points} 分（基础分 100 + 连击奖励 ${combo.value * 10}）`
    
    ElMessage.success(`太棒了！连击 ${combo.value}`)
  } else {
    // 错误
    mistakes.value++
    combo.value = 0
    
    if (mistakes.value >= 3) {
      endGame()
      return
    }
    
    resultType.value = 'error'
    resultMessage.value = '❌ 订单有误'
    
    if (correctSelected < correct) {
      resultDetail.value = `漏选了 ${correct - correctSelected} 个菜品`
    } else if (selected > correct) {
      resultDetail.value = `多选了 ${selected - correct} 个菜品`
    } else {
      resultDetail.value = '选择的菜品不正确'
    }
    
    ElMessage.error('订单错误，请更仔细！')
  }
  
  // 自动进入下一轮
  nextRoundCountdown.value = 3
  const countdownTimer = setInterval(() => {
    nextRoundCountdown.value--
    if (nextRoundCountdown.value <= 0) {
      clearInterval(countdownTimer)
      nextRound()
    }
  }, 1000)
}

// 下一轮
function nextRound() {
  showResult.value = false
  selectedDishes.value = []
  currentOrder.value = generateNewOrder()
  menuOptions.value = getRandomDishes()
  nextRoundCountdown.value = 3
}

// 结束游戏
function endGame() {
  gameStarted.value = false
  finalScore.value = currentScore.value
  showGameOverDialog.value = true
  
  // 更新总体统计
  gameStats.value.points += finalScore.value
  gameStats.value.servedCustomers += servedCount.value
  if (servedCount.value > 0) {
    gameStats.value.accuracy = Math.round(
      ((gameStats.value.accuracy * gameStats.value.servedCustomers + 
        (correctCount.value / servedCount.value * 100) * servedCount.value) / 
        (gameStats.value.servedCustomers + servedCount.value))
    )
  }
}

// 重新开始
function restartGame() {
  showGameOverDialog.value = false
  startGame()
}

// 返回
function goBack() {
  router.push('/learning/games/center')
}
</script>

<style scoped>
.order-taking {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.game-header {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  border-radius: 12px;
  color: #8b4513;
}

.game-title {
  flex: 1;
}

.game-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #8b4513;
}

.game-title p {
  margin: 0;
  color: #a0522d;
}

.game-stats {
  display: flex;
  gap: 40px;
}

.game-stats :deep(.el-statistic__head) {
  color: #a0522d;
}

.game-stats :deep(.el-statistic__content) {
  color: #8b4513;
  font-weight: bold;
}

/* 开始界面 */
.start-screen {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
}

.game-intro {
  background: white;
  border-radius: 16px;
  padding: 48px;
  max-width: 600px;
  text-align: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.game-intro h2 {
  margin: 0 0 32px 0;
  font-size: 28px;
  color: #303133;
}

.rules {
  display: grid;
  gap: 20px;
  margin-bottom: 40px;
  text-align: left;
}

.rule-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.rule-item .el-icon {
  font-size: 24px;
  color: #409eff;
  flex-shrink: 0;
  margin-top: 2px;
}

.rule-item p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

/* 游戏界面 */
.game-screen {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.game-info-bar {
  display: flex;
  justify-content: space-between;
  padding: 16px 24px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.game-info-bar > div {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.timer {
  color: #e6a23c;
}

.score {
  color: #409eff;
}

.combo {
  color: #67c23a;
}

.mistakes {
  color: #f56c6c;
}

/* 餐厅场景 */
.restaurant-scene {
  padding: 24px;
}

.current-customer {
  display: flex;
  align-items: flex-start;
  gap: 24px;
  margin-bottom: 32px;
  padding: 24px;
  background: linear-gradient(135deg, #e0f7fa 0%, #e1f5fe 100%);
  border-radius: 12px;
}

.speech-bubble {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 20px;
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.speech-bubble::before {
  content: '';
  position: absolute;
  left: -10px;
  top: 30px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 10px 10px 10px 0;
  border-color: transparent white transparent transparent;
}

.customer-speech {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
  line-height: 1.8;
  font-weight: 500;
}

.special-requirements {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 菜单网格 */
.menu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.dish-card {
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.dish-card:hover {
  border-color: #409eff;
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.dish-card.selected {
  border-color: #409eff;
  background: #ecf5ff;
}

.dish-card.correct {
  border-color: #67c23a;
  background: #f0f9ff;
}

.dish-card.wrong {
  border-color: #f56c6c;
  background: #fef0f0;
}

.dish-image {
  font-size: 48px;
  margin-bottom: 8px;
}

.dish-card h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.dish-price {
  margin: 0 0 8px 0;
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
}

.dish-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.result-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 24px;
}

.result-icon.correct {
  color: #67c23a;
}

.result-icon.wrong {
  color: #f56c6c;
}

/* 操作按钮 */
.actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

/* 结果面板 */
.result-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.result-panel .el-alert {
  width: 100%;
  max-width: 600px;
}

.next-btn {
  margin-top: 8px;
}

/* 游戏结束 */
.game-over {
  padding: 20px;
}

.final-score {
  text-align: center;
  margin-bottom: 30px;
}

.final-score h2 {
  margin: 0 0 16px 0;
  color: #303133;
}

.score-display {
  font-size: 60px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 16px;
}

.game-stats-summary {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-item {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  text-align: center;
}

.stat-item span {
  display: block;
  margin-bottom: 8px;
  color: #909399;
  font-size: 14px;
}

.stat-item strong {
  font-size: 24px;
  color: #303133;
}
</style>

